/**
 * 
 */
package client;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * <p>
 * Author :HouKangxi <br/>
 * Date : 2013-6-4
 */
public abstract class BaseServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1393954628826222913L;

	protected void execute(String methodName, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (methodName.equals("doGet") || methodName.equals("doPost")) {
			return;
		}
		Method m = PropertyUtil.lookupMethod(getClass(), HttpServlet.class,
				methodName, true, HttpServletRequest.class,
				HttpServletResponse.class);
		if (m == null) {
			PrintWriter out = response.getWriter();
			out.print("error:invalidate URI:" + request.getRequestURI());
			out.close();
			return;
		}
		try {
			m.invoke(this, request, response);
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		work(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		work(request, response);
	}

	protected void work(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setHeader("cache-control", "no-cache");
		setJsonHeader(response);

		String uri = request.getRequestURI();
		{
			int xi = uri.lastIndexOf('/');
			uri = uri.substring(xi + 1);
			uri = uri.substring(0, uri.indexOf('.'));
		}
		String methodName = uri;
		execute(methodName, request, response);
	}

	protected void setHtmlHeader(HttpServletResponse response) {
		response.setContentType("text/html; charset="
				+ response.getCharacterEncoding());
	}

	protected void setJsonHeader(HttpServletResponse response) {
		response.setContentType("application/json; charset="
				+ response.getCharacterEncoding());
	}

}
